﻿using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.BackgroundWorkers.Quartz;

namespace my.abp.Application.Jobs
{
	/// <summary>
	/// 后台定时任务
	/// </summary>
	public class TestBackgroundWorker : QuartzBackgroundWorkerBase
	{

		public TestBackgroundWorker()
		{
			//AutoRegister = false;	// 禁用该后台定时任务
			JobDetail = JobBuilder.Create<TestBackgroundWorker>().WithIdentity(nameof(TestBackgroundWorker)).Build();
			Trigger = TriggerBuilder
			.Create()                               // 创建触发器
			.WithIdentity(nameof(TestBackgroundWorker))      // 触发器名称
			.StartNow()                             // 触发器启动时间为当前
			.WithSimpleSchedule(x => x
				.WithIntervalInSeconds(60)   // 触发器以秒为单位指定重复间隔
				.RepeatForever())                   // 指定触发器将无限期重复
			.Build();

			// 自定义ScheduleJob
			ScheduleJob = async scheduler =>
			{
				// 判断任务是否在于调度作业中,不存在时向quartz添加调度作业.
				if (!await scheduler.CheckExists(JobDetail.Key))
				{
					await scheduler.ScheduleJob(JobDetail, Trigger);
				}
			};
		}
		public override async Task Execute(IJobExecutionContext context)
		{
			// 后台定时任务，非常简单
			var logger = LoggerFactory.CreateLogger<TestBackgroundWorker>();
			logger.LogWarning("Quartz 后台任务管理 测试");
			// var eneities= await _repository.GetListAsync();
			//var entities=   await _sqlSugarClient.Queryable<UserEntity>().ToListAsync();
			//await Console.Out.WriteLineAsync(entities.Count().ToString());
		}
	}
}
